package com.bowos.zmado.service;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * 客户端的Cookies简化处理
 * @author http://www.bowos.com
 */
@Service @Scope("request")
public class CookiesManager {
	/**
	 * 用于存放cookie的容器
	 */
	private Map<String, Cookie> cookies = new HashMap<String, Cookie>();
	/**
	 * http request对像
	 */
	@Autowired
	private HttpServletRequest request;
	/**
	 * http response对像
	 */
	@Autowired
	private HttpServletResponse response;
	
	/**
	 * 初始化cookies容器
	 */
	public CookiesManager(){
		Cookie[] cookies = request.getCookies();
		if(cookies != null){
			for(Cookie cookie:cookies){
				this.cookies.put(cookie.getName(), cookie);
			}
		}
	}

	/**
	 * 添加Cookie到客户端
	 * @param key 键值，Cookie的名称作为键值
	 * @param value Cookie值
	 * @param maxPage 存在时间，以抄为单位
	 */
	public void addCookie(String key, String value, Integer maxPage) {
		Cookie cookie = new Cookie(key, value);
		cookie.setPath("/");
		cookie.setMaxAge(maxPage);
		addCookie(cookie);
	}

	/**
	 * 删除Cookie
	 * @param key 键值
	 */
	public void deleteCookie(String key) {
		Cookie cookie = cookies.get(key);
		if(cookie != null){
			deleteCookie(cookie);
		}
	}

	/**
	 * 根据键值获取获取Cookie
	 * @param key 键值，Cookie的名称作为键值
	 * @return 返回Cookie对像
	 */
	public Cookie getCookie(String key) {
		return cookies.get(key);
	}

	/**
	 * 添加Cookie到客户端
	 * @param cookie Cookie对像
	 */
	public void addCookie(Cookie cookie) {
		response.addCookie(cookie);
	}

	/**
	 * 删除Cookie
	 * @param key 键值
	 */
	public void deleteCookie(Cookie cookie) {
		cookie.setMaxAge(0);
		cookie.setValue(null);
		response.addCookie(cookie);
	}
}
